package com.atguigu.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.order.config.AlipayTemplate;
import com.atguigu.order.service.OrderService;
import com.atguigu.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * description: OrderPayListener
 * date: 2023/1/2 16:52
 * author: MR.孙
 */
@RestController
public class OrderPayListener {

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private OrderService orderService;


    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {

        //只要我们收到了支付宝给我们的异步通知，告诉我们订单支付成功了。返回success，支付宝将不再通知。
        /*    Map<String, String[]> map = request.getParameterMap();
        System.out.println("支付宝异步通知已到位...数据" + map);

        for (String key : map.keySet()) {
            String value = request.getParameter(key);
            System.out.println("参数名：" + key + "\t参数值：" + value);
        }*/

        // 1.验签
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name :requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);

        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if (signVerified) {
            System.out.println("支付宝异步通知验签成功");
            //修改订单状态
            orderService.handlerPayResult(payAsyncVo);
            return "success";
        } else {
            System.out.println("支付宝异步通知验签失败");
            return "error";
        }

    }

}
